package com.tianzeculture.stagebao.activity.home;

import android.content.Intent;
import android.content.res.AssetManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.github.promeg.pinyinhelper.Pinyin;
import com.github.promeg.pinyinhelper.PinyinMapDict;
import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.activity.home.adapter.HistoryCityAdapter;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.WorkTag;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.DensityUtil;
import com.tianzeculture.stagebao.network.util.ToastUtil;
import com.tianzeculture.stagebao.pinyin.CitySortModel;
import com.tianzeculture.stagebao.pinyin.SideBar;
import com.tianzeculture.stagebao.pinyin.SortAdapter;
import com.tianzeculture.stagebao.popwindow.CityModel;
import com.tianzeculture.stagebao.popwindow.ProvinceModel;
import com.tianzeculture.stagebao.popwindow.XmlParserHandler;
import com.tianzeculture.stagebao.util.Util;
import com.tianzeculture.stagebao.view.MyGridView;

import org.greenrobot.eventbus.EventBus;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/5/30 0030.
 */

public class SelectCityActivity extends BaseActivity {
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.lvCity)
    ListView lvCity;
    @BindView(R.id.sideBar)
    SideBar sideBar;
    @BindView(R.id.tvHint)
    TextView tvHint;

    boolean noEventBus;

    private SortAdapter adapter;

    List<CitySortModel> sortModels = new ArrayList<>();//排序的城市列表
    List<CityModel> cityModels = new ArrayList<>();

    String cityName;

    @Override
    public void initUI() {
        super.initUI();
        cityName = getIntent().getStringExtra("CITY");
        noEventBus = getIntent().getBooleanExtra("noEventBus", false);
        if ("".equals(cityName) || cityName == null) {
            cityName = "杭州";
        }
        tvTitle.setText("当前城市 - " + cityName);
        initAllCityDatas();
        getAllData();

        adapter = new SortAdapter(this, sortModels);
        lvCity.setAdapter(adapter);

        ViewGroup.LayoutParams params = sideBar.getLayoutParams();
        params.height = DensityUtil.getScreenHeight(this) * 7 / 10;
        sideBar.setLayoutParams(params);

        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int a1 = getCurrentPosition(s);
                if (a1 != -1) {
                    lvCity.setSelection(a1);
                    tvHint.setVisibility(View.VISIBLE);
                    tvHint.setText(s);
                }
            }
        });
        sideBar.setTextView(tvHint);


        lvCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (noEventBus) {
                    Intent intent = getIntent();
                    intent.putExtra("CITY", sortModels.get(i - 1).getName());
                    setResult(Util.SELECT_CITY, intent);
                } else {
                    WorkTag tag = new WorkTag();
                    tag.setName(sortModels.get(i - 1).getName());
                    EventBus.getDefault().post(tag);
                }
                finish();
            }
        });

        initCityHeader();
    }

    /**
     * ListVIew
     */
    private void initCityHeader() {
        View view = LayoutInflater.from(this).inflate(R.layout.item_city_header, null);
        final TextView tvLocation = view.findViewById(R.id.tvLocation);
        MyGridView gvHistory = view.findViewById(R.id.gvHistory);
        tvLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ToastUtil.showCenter(SelectCityActivity.this, tvLocation.getText().toString().trim());
                Intent intent = new Intent();
                intent.putExtra("CITY", tvLocation.getText().toString().trim());
                setResult(Util.SELECT_CITY, intent);
                finish();
            }
        });
        ViewGroup.LayoutParams params = tvLocation.getLayoutParams();
        params.width = DensityUtil.getScreenWidth(this) * 1 / 4;
        tvLocation.setLayoutParams(params);
        List<String> citys = new ArrayList<>();

        HistoryCityAdapter adapter = new HistoryCityAdapter(this, citys);
        gvHistory.setAdapter(adapter);
        lvCity.addHeaderView(view);
    }


    private Map<String, Integer> map = new HashMap<>();

    /**
     * list获取所有数据
     */
    private void getAllData() {
        Pinyin.init(Pinyin.newConfig()
                .with(new PinyinMapDict() {
                    @Override
                    public Map<String, String[]> mapping() {
                        HashMap<String, String[]> map = new HashMap<String, String[]>();
                        map.put("重庆", new String[]{"CHONG", "QING"});
//                        map.put("不限", new String[]{"#", "BU", "XIAN"});
                        return map;
                    }
                }));

        for (int i = 0; i < cityModels.size(); i++) {
            //将汉字转换为拼音
            String string = Pinyin.toPinyin(cityModels.get(i).getName(), "");
            //将拼音字符串转换为大写拼音
            String pinD = String.valueOf(string.charAt(0)).toUpperCase();
            CitySortModel sortModel = new CitySortModel();
            sortModel.setName(cityModels.get(i).getName());
            //获取大写拼音字符串的第一个字符
            char c1 = pinD.charAt(0);
            if (c1 < 'A' || c1 > 'Z') {
                sortModel.setSortLetters("#");
            } else {
                sortModel.setSortLetters(String.valueOf(c1));
            }
            sortModels.add(sortModel);
        }
        //将联系人列表的标题字母排序
        Collections.sort(sortModels, new Comparator<CitySortModel>() {
            @Override
            public int compare(CitySortModel o1, CitySortModel o2) {
                return o1.getSortLetters().compareTo(o2.getSortLetters());
            }
        });
        //记录字母所在位置
        String s1 = sortModels.get(0).getSortLetters();
        map.put(s1, 0);
        for (int i = 0; i < sortModels.size(); i++) {
            String s2 = sortModels.get(i).getSortLetters();
            if (!s1.equals(s2)) {
                s1 = s2;
                map.put(s2, i);
            }
        }
    }

    private int getCurrentPosition(String s) {
        if (map.get(s) != null) {
            return map.get(s);
        } else {
            return -1;
        }
    }


    @Override
    public void refreshUI(int taskId, MSG msg) {
        super.refreshUI(taskId, msg);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_select_city;
    }


    /**
     * 初始化数据
     */
    protected void initAllCityDatas() {
        List<CityModel> citys = new ArrayList<>();
        List<ProvinceModel> provinceList = null;
        AssetManager asset = getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            provinceList = handler.getDataList();
            String[] mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                citys.addAll(cityList);
            }

            cityModels = removeDuplicate(citys);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
        }
    }


    private List<CityModel> removeDuplicate(List<CityModel> oldCityModels) {
        List<CityModel> newCityModels = new ArrayList<>();
        for (int i = 0; i < oldCityModels.size(); i++) {
            boolean isHas = false;
            for (int j = 0; j < newCityModels.size(); j++) {
                if (newCityModels.get(j).getName().equals(oldCityModels.get(i).getName())) {
                    isHas = true;
                }
            }

            if (!isHas) {
                newCityModels.add(oldCityModels.get(i));
            }
        }

        return newCityModels;
    }


}
